<template>
  <div class="container">
    <h1 class="lock-title">我的</h1>
    <div class="sidebar">
      <div class="user-info" style="display: flex; align-items: center; padding: 20px;">
        <van-avatar
            size="large"
            :src="user.avatarUrl || 'https://img.keaitupian.cn/newupload/11/1668419337598639.jpg'"
            style="margin-right: 10px;"
        />
        <div class="user-details" @click="puthGeren">
          <div class="user-avatar" @click="uploadAvatar">
            <img :src="user.avatarUrl" style="width: 30px; height: 30px;">
          </div>
          <div class="user-name" style="font-size: 16px; color: #333;">{{ user.username }}</div>
        </div>
      </div>
      <div class="menu">
        <button @click="changePassword" class="custom-button">
          修改密码 <i class="el-icon-unlock"></i>
        </button>
        <button @click="inviteFriend" class="custom-button">
          完善信息 <i class="el-icon-user"></i>
        </button>
        <button @click="showPoints" class="custom-button">
          积分&优惠券 <i class="el-icon-present"></i>
        </button>
        <button @click="helpCenter" class="custom-button">
          帮助中心 <i class="el-icon-warning-outline"></i>
        </button>
        <button @click="payment" class="custom-button">
          支付 <i class="el-icon-bank-card"></i>
        </button>
        <button @click="settings" class="custom-button">
          设置 <i class="el-icon-setting"></i>
        </button>
      </div>
    </div>
    <!--    底部导航-->
    <div class="bottom-navigation">
      <button @click="discover"><i class="el-icon-search"></i><br />发现</button>
      <button @click="travel"><i class="el-icon-star-off"></i><br />旅行</button>
      <button @click="myProfile"><i class="el-icon-user"></i><br />我的</button>
    </div>
    <input type="file" id="avatarUpload" style="display: none;" @change="handleAvatarUpload">
  </div>
</template>

<script>
import OSS from 'ali-oss';

export default {
  data() {
    return {
      active: 3,
      user: {},
      count: 0,
      aount: 0,
      ossClient: null
    };
  },
  created() {
    const userStr = sessionStorage.getItem("user");
    this.user = JSON.parse(userStr);
    // 初始化 OSS 客户端
    this.ossClient = new OSS({
      region: 'oss-cn-beijing',// 替换为你的 OSS 区域，例如 'oss-cn-hangzhou'
      accessKeyId: 'LTAI5tRwVJqmVXE9ym1o7Z3r', // 替换为你的 AccessKey ID
      accessKeySecret: 'OqHoz9iZnABH9Y3q9aOsF7Gvjz18se',// 替换为你的 AccessKey Secret
      bucket: 'touxiangsc' // 替换为你的存储空间名称
    });
  },
  methods: {
    changePassword() {
      alert('修改密码');
    },
    inviteFriend() {
      this.$router.push('/wan');
    },
    showPoints() {
      alert('积分&优惠券');
    },
    helpCenter() {
      alert('帮助中心');
    },
    payment() {
      alert('支付');
    },
    settings() {
      alert('设置');
    },
    discover() {
      if (this.$route.path !== '/homePage') {
        this.$router.push(`/homePage`);
        this.$router.go(0);
      }
    },
    travel() {
      this.$router.push('/travel');
      this.$router.go(0);
    },
    myProfile() {
      this.$router.push('/Wo');
    },
    uploadAvatar() {
      document.getElementById('avatarUpload').click();
    },
    async handleAvatarUpload(event) {
      const file = event.target.files[0];
      if (file) {
        try {
          const fileName = `avatars/${Date.now()}-${file.name}`;
          const result = await this.ossClient.put(fileName, file);
          const avatarUrl = result.url;
          this.user.avatarUrl = avatarUrl;
          sessionStorage.setItem('user', JSON.stringify(this.user));
          // 发送请求将图片 URL 保存到数据库
          await this.saveAvatarToDatabase(avatarUrl);
          this.$message.success('头像上传成功');
          this.$router.go(0);
        } catch (error) {
          console.error('头像上传失败:', error);
          alert('头像上传失败，请稍后重试');
        }
      }
    },
    async saveAvatarToDatabase(avatarUrl) {
      try {
        const response = await fetch('http://localhost:6001/user/update', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            userid: this.user.userid, // 假设用户信息中有 id
            avatarUrl: avatarUrl
          })
        });
        const data = await response.json();
        if (data.success) {
          console.log('头像信息保存到数据库成功');
        } else {
          console.error('头像信息保存到数据库失败:', data.message);
        }
      } catch (error) {
        console.error('保存头像信息到数据库时出错:', error);
      }
    }
  }
};
</script>

<style>
.custom-button {
  font-size: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%; /* 根据需要调整宽度 */
  padding: 10px; /* 根据需要调整内边距 */
  border-radius: 5px; /* 根据需要调整圆角 */
  background-color: #fff; /* 根据需要调整背景色 */
}

.custom-button i {
  margin-left: auto; /* 确保图标靠右 */
}

.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  background-color: #008000;
}

.user-name {
  font-size: 20px;
  font-weight: bold;
}

.user-avatar {
  width: 20px;
  height: 20px;
  border-radius: 50%;
}

.sidebar {
  width: 93%;
  height: 100%;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.profile,
.menu {
  margin-bottom: 20px;
}

.profile span {
  display: block;
  margin-bottom: 10px;
  font-size: 18px;
  font-weight: bold;
}

button {
  display: block;
  width: 100%;
  padding: 10px;
  margin-bottom: 10px;
  background-color: #fff;
  border: none; /* 移除了边框 */
  border-radius: 4px;
  cursor: pointer;
}

button:hover {
  background-color: #d0d0d0;
}

.bottom-navigation {
  position: fixed;
  bottom: 0;
  width: 100%;
  display: flex;
  justify-content: space-around;
  background-color: #fff;
  padding: 10px 0;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
  z-index: 1000; /* 确保它在其他内容之上 */
}

.bottom-navigation button {
  flex: 1;
  margin: 0 10px;
}
</style>
